package com.kuaishou.locallife.open.api.common.utils;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 本地日志相关工具类
 *
 * @author shuxiaohui <shuxiaohui@kuaishou.com>
 * Created on 2020-03-31
 */
public class LoggerUtils {

    /**
     * 输出api异常本地日志
     * @param logger logger对象
     * @param appKey 应用key
     * @param apiMethod  api方法
     * @param url 目标url
     * @param params 请求参数
     * @param throwable 异常类型
     */
    public static void logApiError(Logger logger, String appKey, String apiMethod, String url, Map<String, String > params, Throwable throwable) {
        StringBuilder logStr = new StringBuilder();
        logStr.append(formatDateTime(new Date()));
        logStr.append("*_*");
        logStr.append(appKey);
        logStr.append("*_*");
        logStr.append(apiMethod);
        logStr.append("*_*");
        logStr.append(url);

        try {
            logStr.append("*_*");
            logStr.append(WebUtils.buildQueryParams(params, "UTF-8"));
        } catch (IOException ignored) {
        }

        logger.log(Level.WARNING, logStr.toString(), throwable);
    }

    public static void logApiError(Logger logger, String apiMethod, String url, Map<String, String > params, Throwable throwable) {
        StringBuilder logStr = new StringBuilder();
        logStr.append(formatDateTime(new Date()));
        logStr.append("*_*");
        logStr.append("*_*");
        logStr.append(apiMethod);
        logStr.append("*_*");
        logStr.append(url);

        try {
            logStr.append("*_*");
            logStr.append(WebUtils.buildQueryParams(params, "UTF-8"));
        } catch (IOException ignored) {
        }

        logger.log(Level.WARNING, logStr.toString(), throwable);
    }

    public static void info(Logger logger, String content) {
        logger.log(Level.INFO, buildLogContent(content));
    }

    public static void warn(Logger logger, String content) {
        logger.log(Level.WARNING, buildLogContent(content));
    }

    private static String buildLogContent(String content) {
        StringBuilder logStr = new StringBuilder();
        logStr.append(formatDateTime(new Date()));
        logStr.append(": ");
        logStr.append(content);

        return logStr.toString();
    }

    private static String formatDateTime(Date date) {
        return KsStringUtils.formatDateTime(date, "yyyy-MM-dd HH:mm:ss.SSS");
    }

    private LoggerUtils() {
    }
}
